package twitter.RequestHandler;

import java.io.PrintWriter;
import java.util.Collection;
import java.util.Iterator;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Logger;

import Twitter.RequestSender.RequestSender;
import Twitter.RequestSender.ServerRegistrationSender;

import twitter.Server.ServerType;
import twitter.TwitterLibrary.SocketConfig;
import twitter.TwitterLibrary.Utility;

public class ElectionNoticeHandler extends HTTPRequestHandler {
	private static Logger logger = Logger.getLogger(DeleteServerHandler.class);
	private final ReentrantReadWriteLock rwl;
	private final Lock r;
	private final Lock w;
	private Utility utility;
	private RequestSender sender;

	public ElectionNoticeHandler(ReentrantReadWriteLock rwl, Utility utility) {
		super(rwl, utility);
		BasicConfigurator.configure();
		this.rwl = rwl;
		this.r = rwl.readLock();
		this.w = rwl.writeLock();
		this.utility = utility;
		this.sender = new RequestSender(utility);
		// TODO Auto-generated constructor stub
	}

	@Override
	public void parseHttpRequest(String httpInput, PrintWriter httpOutput) {
		// TODO Auto-generated method stub
		String query = httpInput.substring(0, httpInput.indexOf("election"));
		StringTokenizer st = new StringTokenizer(query);
		String server = st.nextToken();
		//String tempIdentifier = st.nextToken();
		System.out.println("*******************received one election server information");
		logger.info("in election received one election server information");
		httpOutput.print("election response");
		httpOutput.flush();
		Collection Servers = SocketConfig.identifierToServer.values();
		sender.startElection(Servers, SocketConfig.primaryIp);
		// String result=parser.readQueries(query);

		// String servers=query.substring(query.indexOf(" "));
		// System.out.println("***********In notice response ********primary server receive one notice response message "+query);
/*
		this.utility.electionResponseResult.clear();

		if (Integer.parseInt(tempIdentifier) < SocketConfig.identifier) {

			httpOutput.print("election response");
			httpOutput.flush();

			Set ServerIdentifiers2 = SocketConfig.identifierToServer.keySet();
			Iterator itertt2 = ServerIdentifiers2.iterator();
			String election = SocketConfig.myIp + " " + SocketConfig.identifier
					+ "\r\n election \r\n";
			while (itertt2.hasNext()) {

				int tempIdentifier2 = Integer.parseInt(itertt2.next()
						.toString());
				System.out.println("************" + tempIdentifier2);
				String serverip2 = SocketConfig.identifierToServer
						.get(String.valueOf(tempIdentifier2));
				logger.info("in election : ((SocketConfig.identifier < tempIdentifier2)&& " +
						"(SocketConfig.serverToType.get(serverip2)" +
						" == ServerType.BackendServer)) "+((SocketConfig.identifier < tempIdentifier2)
						&& (SocketConfig.serverToType.get(serverip2) == ServerType.BackendServer)) );
				logger.info("in election: my identifier: "+SocketConfig.identifier);
				logger.info("in election: another server 's identifier:"+tempIdentifier2);
				logger.info("in selection : SocketConfig.serverToType.get(serverip2) "+SocketConfig.serverToType.get(serverip2));
				if ((SocketConfig.identifier < tempIdentifier2)
						&& (SocketConfig.serverToType.get(serverip2) == ServerType.BackendServer)) {
					System.out.println("*********************************************in election : there is someone is bigger" +
							" than me the ip is"+serverip2+" and my ip is "+SocketConfig.myIp);
					logger.info("in election : there is someone  bigger" +
							" than me the ip is"+serverip2+" and my ip is SocketConfig.myIp");
					String response = sender.sendRequest(serverip2, election,
							SocketConfig.backendPort);
					if ((response != null) && (!response.equals(""))) {
						utility.electionResponseResult.add(serverip2);
					}
				}
			}

			if (utility.electionResponseResult.size() == 0) {
				SocketConfig.serverType = ServerType.PrimaryServer;
				SocketConfig.primaryIp = SocketConfig.myIp;
				if(SocketConfig.serverToType.get(SocketConfig.primaryIp)==ServerType.BackendServer)
				{
					SocketConfig.serverToType.put(SocketConfig.primaryIp, ServerType.PrimaryServer);
					System.out.println("|||||||||||||||||change my tpye from back end to primary server");
				}
				
				ServerRegistrationSender registration = new ServerRegistrationSender(
						this.utility);
				utility.threadPool.execute(registration);
			}
			else
			{
				logger.info("I give up my election");
			}

			// *************************

		}
		*/
		
		
		
		
	}
	

}
